package com.nf.health.app.inquiry;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.nf.health.app.R;
import com.nf.health.app.core.HttpActionHandle;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.Apis;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.http.VolleyErrorHelper;
import com.nf.health.app.utils.MathUtils;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.pay.PayResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


/**
 * Created by changpeng on 2016/10/8.
 * UI修改: 2016/12/20
 * 送心意Dialog
 */
public class InquirySendHeartDialog extends Dialog implements HttpActionHandle, View.OnClickListener {

    private String doctorId;
    private Context ctx;
    private View mContent;
    private String doctorName;
    private EditText etHealthMoney;
    private EditText etMoney;
    private TextView tvHealthMoneyRemain;
    private TextView mTvOne;
    private TextView mTvThree;
    private TextView mTvFive;
    private TextView mTvTen;
    private TextView mTvFifteen;
    private TextView mTvTwenty;
    private RadioButton mRbHealthMoney;
    private RadioButton mRbHeart;
    private TextView sendHeartTitle;
    private RelativeLayout mRlRow1;
    private RelativeLayout mRlRow2;
    private TextView mTvCoin;
    private TextView mTvMoney;


    public static final String GET_USER_SCORE = "getUserScore";
    public static final int HEALTH_MONEY = 1;
    public static final int HEART = 2;

    /*支付宝支付结果码*/
    private static final String PAY_OK = "9000";// 支付成功
    private static final  String PAY_WAIT_CONFIRM = "8000";// 交易待确认
    private static final String PAY_NET_ERR = "6002";// 网络出错
    private static final String PAY_CANCLE = "6001";// 交易取消
    private static final String PAY_FAILED = "4000";// 交易失败/*内部类，处理支付宝支付结果*/
    private static final int SDK_PAY_FLAG = 1;

    private RequestProvider provider;
    private int mSendType = HEALTH_MONEY; // 默认为健康币
    private static InquirySendHeartDialog singleDialog = null;
    private boolean isClickConfirm = false;
    private Button btnSendHeartConfirm;

    private boolean[] selectState = new boolean[]{false, false, false, false, false, false};
    private int[] money = new int[]{1, 3, 5, 10, 15, 20};
    private String mHealthMoenyNum;

    public InquirySendHeartDialog(Context context, String doctorName, String doctorId) {
        //设置style
        super(context, R.style.dialog3);
        this.ctx = context;
        this.doctorName = doctorName;
        this.doctorId = doctorId;
        init();
    }

    //初始化
    private void init() {
        provider = new RequestProvider(InquirySendHeartDialog.this);
        setContentView(R.layout.dialog_send_heart);
        mContent = findViewById(R.id.ll_content);
        sendHeartTitle = (TextView) findViewById(R.id.tv_send_heart_title);
        mTvOne = (TextView) findViewById(R.id.tv_one);
        mTvThree = (TextView) findViewById(R.id.tv_three);
        mTvFive = (TextView) findViewById(R.id.tv_five);
        mTvTen = (TextView) findViewById(R.id.tv_ten);
        mTvFifteen = (TextView) findViewById(R.id.tv_fifteen);
        mTvTwenty = (TextView) findViewById(R.id.tv_twenty);
        tvHealthMoneyRemain = (TextView) findViewById(R.id.tv_health_money_remain);
        etHealthMoney = (EditText) findViewById(R.id.et_health_money);
        etMoney = (EditText) findViewById(R.id.et_money);
        mRlRow1 = (RelativeLayout) findViewById(R.id.rl_row1);
        mRlRow2 = (RelativeLayout) findViewById(R.id.rl_row2);
        mRbHealthMoney = (RadioButton) findViewById(R.id.rb_health_money);
        mRbHeart = (RadioButton) findViewById(R.id.rb_heart);
        btnSendHeartConfirm = (Button) findViewById(R.id.btn_send_heart_confirm);
        mTvCoin = (TextView) findViewById(R.id.tv_coin);
        mTvMoney = (TextView) findViewById(R.id.tv_money);
        initListener();
        initData();
        //设置大小
        FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) mContent.getLayoutParams();
        p.width = (int) (ScreentUtils.getScreenWidth(ctx) * .8); //宽度占屏幕宽度的80%
        mContent.setLayoutParams(p);

        mRbHealthMoney.setChecked(true);
        mRbHeart.setChecked(false);
        mRlRow1.setVisibility(View.GONE);
        mRlRow2.setVisibility(View.GONE);
        changeTextViewColor(true);

    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            clearSelectedState();
        }
    };
    private void initListener() {
        btnSendHeartConfirm.setOnClickListener(this);
        mRbHealthMoney.setOnClickListener(this);
        mRbHeart.setOnClickListener(this);
        mTvOne.setOnClickListener(this);
        mTvThree.setOnClickListener(this);
        mTvFive.setOnClickListener(this);
        mTvTen.setOnClickListener(this);
        mTvFifteen.setOnClickListener(this);
        mTvTwenty.setOnClickListener(this);

        etMoney.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        mRbHeart.setChecked(true);
                        mSendType = HEART;
                        changeView(mSendType);
                        break;
                }
                return false;
            }
        });
        etHealthMoney.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        mRbHealthMoney.setChecked(true);
                        mSendType = HEALTH_MONEY;
                        changeView(mSendType);
                        break;
                }
                return false;
            }
        });

        etMoney.addTextChangedListener(mTextWatcher);
    }

    private void initData() {
        if (!TextUtils.isEmpty(doctorName)) {
            sendHeartTitle.setText("送" + doctorName + "医生心意！谢谢医生细心的解答！");
        }

      /*  provider.getUserScore(GET_USER_SCORE);*/
        //请求将健康的个数
        provider.getUserHealthMoenyNUm();
    }

    @Override
    protected void onStart() {
        super.onStart();
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }

    @Override
    public void handleActionStart(String actionName, Object object) {

    }

    @Override
    public void handleActionFinish(String actionName, Object object) {

    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        Toast.makeText(getContext(), VolleyErrorHelper.getMessage(error), Toast.LENGTH_LONG).show();
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (Act.Flag.PERSONALLY_MONEY.equals(actionName)) {
            provider.getUserHealthMoenyNUm();
            Toast.makeText(getContext(), "您的心意已到达，谢谢支持！", Toast.LENGTH_LONG).show();
        } else if (Act.Flag.FLAG_GET_USERHEALTH_MOENY_COUNT.equals(actionName)) {
            try {
                mHealthMoenyNum =object.toString();
                if (!TextUtils.isEmpty(mHealthMoenyNum)) {
                    tvHealthMoneyRemain.setText("您剩余" + mHealthMoenyNum + "健康币");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        if(Act.Flag.CREATE_MIND_ORDER_FLAG.equals(actionName)){
            String orderno = (String) object; // 拿到订单
            provider.createServiceOrder(orderno); //验签
        }

        if(Act.Flag.ALIPAYSIGN_FLAG.equals(actionName)){
            String signFlag = object.toString();
            if(!TextUtils.isEmpty(signFlag)){
                payToOrderService(signFlag);
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_heart_confirm:
                commit();
                break;
            case R.id.rb_health_money:
                mSendType = HEALTH_MONEY;
                changeView(mSendType);
                break;
            case R.id.rb_heart:
                mSendType = HEART;
                changeView(mSendType);
                break;
            case R.id.tv_one:
                selectedMoney(0);
                break;
            case R.id.tv_three:
                selectedMoney(1);
                break;
            case R.id.tv_five:
                selectedMoney(2);
                break;
            case R.id.tv_ten:
                selectedMoney(3);
                break;
            case R.id.tv_fifteen:
                selectedMoney(4);
                break;
            case R.id.tv_twenty:
                selectedMoney(5);
                break;

        }
    }

    private void commit() {
        if (mSendType == HEALTH_MONEY) {
            isClickConfirm = true;
            String healthMoney = etHealthMoney.getText().toString().trim();
            if (!TextUtils.isEmpty(healthMoney) && Double.parseDouble(healthMoney) > 0 ) {
                if(Double.parseDouble(mHealthMoenyNum) < Double.parseDouble((healthMoney))){
                    Toast.makeText(getContext(), "输入健康币不小于0！", Toast.LENGTH_LONG).show();
                    return;
                }
                provider.personallyMoney(doctorId, MathUtils.getFloats(Double.parseDouble(healthMoney) * 100));
            } else {
                Toast.makeText(getContext(), "输入健康币不小于0!", Toast.LENGTH_LONG).show();
                return;
            }
            dismiss();
        }

        if (mSendType == HEART) {
            int m = 0;
            if(Apis.HOST_COMMON.contains("test.")){ // 线下
                m = getMoney();         //接口单位是分
            }else{
                m = getMoney() * 100;   //单位改为元
            }
            if(m != 0){
                provider.createMindOrder(doctorId,m + "");
            }
        }
    }

    /**
     * 选择送心意额度
     *
     * @param selectedIndex 取值范围 0 - 5
     */
    private void selectedMoney(int selectedIndex) {
        //如果 是 -1 则代表清除选中状态
        if(selectedIndex != -1) {
            etMoney.removeTextChangedListener(mTextWatcher);
            etMoney.setText("");
            etMoney.addTextChangedListener(mTextWatcher);
        }
        for (int i = 0; i < selectState.length; i++) {
            if (i == selectedIndex) {
                selectState[i] = true;
            } else {
                selectState[i] = false;
            }
        }
        mTvOne.setSelected(selectState[0]);
        mTvThree.setSelected(selectState[1]);
        mTvFive.setSelected(selectState[2]);
        mTvTen.setSelected(selectState[3]);
        mTvFifteen.setSelected(selectState[4]);
        mTvTwenty.setSelected(selectState[5]);
    }

    /**
     * 获取要送的金钱数量
     * @return
     */
    private int getMoney(){
        for (int i = 0; i < selectState.length; i++) {
            if(selectState[i]){
                return money[i];
            }
        }
        String numS = etMoney.getText().toString();
        if(!TextUtils.isEmpty(numS)){
            int num = Integer.parseInt(numS);
            if(num < 21 || num > 288){
                Toast.makeText(getContext(),"输入金额不合理",Toast.LENGTH_LONG).show();
                return 0;
            }
            return num;
        }
        Toast.makeText(getContext(),"输入金额不合理",Toast.LENGTH_LONG).show();
        return 0;
    }

    private void clearSelectedState(){
        selectedMoney(-1);
    }

    private void payToOrderService(final String signInfo) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                PayTask payTask = new PayTask((Activity) ctx);
                // String result = payTask.pay(signInfo, true);
                Map<String, String> result = payTask.payV2(signInfo, true);
                Message message = mHandler.obtainMessage();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);

            }
        }.start();
    }


    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SDK_PAY_FLAG:
                    PayResult payResult = null;
                    try{
                        payResult = new PayResult((Map<String, String>) msg.obj);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, PAY_OK)) {//----------------------------------->支付成功
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(getContext(),"支付成功",Toast.LENGTH_LONG).show();
                        dismiss();
                    } else if (TextUtils.equals(resultStatus, PAY_FAILED)) {//------------------------->支付失败
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getContext(),""+payResult.getMemo(),Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_CANCLE)) {//-------------------------->交易取消
                        Toast.makeText(getContext(),""+payResult.getMemo(),Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_NET_ERR)) {//------------------------->网络出现错误
                        Toast.makeText(getContext(),""+payResult.getMemo(),Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_WAIT_CONFIRM)) {//--------------------->交替等待
                    }
                    break;
            }
        }
    };

    /**
     * 改变textView颜色
     * @param checked true 代表健康币选中  false 代表送心意选中
     */
    private void changeTextViewColor(boolean checked){
        int selectedColor = getContext().getResources().getColor(R.color.common_font_black_two_color);
        int defaultColor = getContext().getResources().getColor(R.color.common_font_gray_color);
        if(checked) {
            mRbHealthMoney.setTextColor(selectedColor);
            mRbHeart.setTextColor(defaultColor);
            mTvMoney.setTextColor(defaultColor);
            mTvCoin.setTextColor(selectedColor);
        }else{
            mRbHealthMoney.setTextColor(defaultColor);
            mRbHeart.setTextColor(selectedColor);
            mTvMoney.setTextColor(selectedColor);
            mTvCoin.setTextColor(defaultColor);
        }
    }

    /**
     * 改变相关View的状态
     * @param sendType
     */
    private void changeView(int sendType){
        if(sendType == HEALTH_MONEY){
            etMoney.setCursorVisible(false);
            etHealthMoney.setCursorVisible(true); // 设置光标是否显示
            etHealthMoney.requestFocus();
            mRbHeart.setChecked(false);
            mRlRow1.setVisibility(View.GONE);
            mRlRow2.setVisibility(View.GONE);
            changeTextViewColor(true);
            etMoney.removeTextChangedListener(mTextWatcher);
            etMoney.setText("");
            etMoney.addTextChangedListener(mTextWatcher);
        }

        if(sendType == HEART){
            etMoney.setCursorVisible(true);
            etHealthMoney.setCursorVisible(false);
            etMoney.requestFocus();
            mRbHealthMoney.setChecked(false);
            mRlRow1.setVisibility(View.VISIBLE);
            mRlRow2.setVisibility(View.VISIBLE);
            changeTextViewColor(false);
            etHealthMoney.setText("");
        }
    }

}
